import tkinter as tk
from tkinter import ttk
from utils import log_exception

class PlaceholderEntry(ttk.Entry):
    """自定义带 placeholder 的输入框（解决密码框 placeholder 显示问题）"""
    def __init__(self, master=None, placeholder="", color="grey", is_password=False, bg=None, background=None, *args, **kwargs):
        # 处理背景色参数
        bg_color = bg or background or "#fefefe"  # 默认使用#fefefe
        
        # 先初始化父类
        super().__init__(master, *args, **kwargs)
        
        # 获取默认前景色
        self.default_fg_color = self.cget("foreground")
        
        # 处理背景色参数
        bg_color = bg or background or "#fefefe"  # 默认使用#fefefe
        
        # 创建自定义样式以覆盖主题
        style_name = f"CustomPlaceholderEntry{id(self)}.TEntry"
        if master and hasattr(master, 'style'):
            style = master.style
        else:
            from ttkbootstrap import Style
            style = Style()
        
        # 配置自定义样式，完全移除所有边框相关属性
        style.configure(style_name,
            fieldbackground=bg_color,
            background=bg_color,
            borderwidth=0,
            highlightthickness=0,
            relief="flat",
            padding=0,
            bordercolor=bg_color,
            highlightcolor=bg_color,
            highlightbackground=bg_color,
            troughcolor=bg_color,
            selectbackground=bg_color,
            selectforeground=self.default_fg_color,
            # 添加额外的边框属性覆盖
            lightcolor=bg_color,
            darkcolor=bg_color,
            focuscolor=bg_color
        )
        
        # 确保在所有状态下都没有边框
        style.map(style_name,
            borderwidth=[('!disabled', 0), ('disabled', 0), ('focus', 0)],
            highlightthickness=[('!disabled', 0), ('disabled', 0), ('focus', 0)],
            relief=[('!disabled', 'flat'), ('disabled', 'flat'), ('focus', 'flat')],
            bordercolor=[('!disabled', bg_color), ('disabled', bg_color), ('focus', bg_color)],
            highlightcolor=[('!disabled', bg_color), ('disabled', bg_color), ('focus', bg_color)],
            highlightbackground=[('!disabled', bg_color), ('disabled', bg_color), ('focus', bg_color)],
            fieldbackground=[('!disabled', bg_color), ('disabled', bg_color), ('focus', bg_color)],
            # 添加额外的状态映射
            lightcolor=[('!disabled', bg_color), ('disabled', bg_color), ('focus', bg_color)],
            darkcolor=[('!disabled', bg_color), ('disabled', bg_color), ('focus', bg_color)],
            focuscolor=[('!disabled', bg_color), ('disabled', bg_color), ('focus', bg_color)]
        )
        
        # 完全重置布局，移除所有可能的边框元素
        try:
            # 获取当前布局
            layout = style.layout('TEntry')
            # 移除边框相关的元素
            new_layout = []
            for element in layout:
                if 'border' not in element[0] and 'focus' not in element[0]:
                    new_layout.append(element)
            # 应用新布局
            style.layout(style_name, new_layout)
        except Exception as e:
            # 如果出现错误，记录但继续执行
            log_exception(f"Error modifying layout: {e}")
            pass
        
        # 应用自定义样式
        self.configure(style=style_name)
        self.placeholder = placeholder
        self.placeholder_color = color
        self.is_placeholder_active = False
        self.is_password = is_password  # 标记是否是密码输入框
        
        # 保存原始的 show 设置
        self.original_show = kwargs.get('show', '')
        
        # 如果创建时指定了 show 参数，保存它
        if 'show' in kwargs:
            self.original_show = kwargs['show']
        
        self.bind("<FocusIn>", self.on_focus_in)
        self.bind("<FocusOut>", self.on_focus_out)
        self.bind("<KeyPress>", self.on_key_press)
        
        self.put_placeholder()
    
    def put_placeholder(self):
        """显示 placeholder"""
        if not self.get():
            self.delete(0, tk.END)
            self.insert(0, self.placeholder)
            self.config(foreground=self.placeholder_color)
            
            # 密码框在显示 placeholder 时不应用星号显示
            if self.is_password:
                self.config(show="")  # 显示明文 placeholder
            
            self.is_placeholder_active = True
    
    def remove_placeholder(self):
        """移除 placeholder"""
        if self.is_placeholder_active:
            self.delete(0, tk.END)
            self.config(foreground=self.default_fg_color)
            
            # 密码框在用户输入时应用星号显示
            if self.is_password and self.original_show:
                self.config(show=self.original_show)
            
            self.is_placeholder_active = False
    
    def on_focus_in(self, event):
        """当输入框获得焦点时"""
        if self.is_placeholder_active:
            self.remove_placeholder()
    
    def on_focus_out(self, event):
        """当输入框失去焦点时"""
        if not self.get():
            self.put_placeholder()
    
    def on_key_press(self, event):
        """当按键按下时"""
        # 如果当前显示 placeholder，移除它
        if self.is_placeholder_active:
            self.remove_placeholder()
            
            # 重新处理当前按键（如果它是可打印字符）
            if event.char and event.char.isprintable():
                self.insert(tk.INSERT, event.char)
                return "break"  # 阻止默认处理
    
    def get_real_value(self):
        """获取真实值（过滤 placeholder）"""
        if self.is_placeholder_active:
            return ""
        return self.get()
    
    def set_value(self, value):
        """设置输入框的值（自动处理 placeholder 状态）"""
        self.remove_placeholder()  # 确保移除 placeholder
        
        if value:
            self.delete(0, tk.END)
            self.insert(0, value)
            self.config(foreground=self.default_fg_color)
            
            # 如果是密码框且设置了原始显示方式，应用它
            if self.is_password and self.original_show:
                self.config(show=self.original_show)
        else:
            self.put_placeholder()
    
    def is_placeholder_displayed(self):
        """检查当前是否显示 placeholder"""
        return self.is_placeholder_active